#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <map>
#include <vector>
#include <string>

bool LoadCharTable(const char* path, std::map<unsigned int, std::vector<unsigned int> > &r);
void Show(const std::vector<unsigned int>& ch);
unsigned int Line2Code(char *line, std::vector<unsigned int> &code);

int main(int argc, char* argv[]) {
  if (argc != 3) {
    printf("usage:./si <chartable path> <unicode>\n");
    return 1;
  }
  std::map<unsigned int, std::vector<unsigned int> > table;
  LoadCharTable(argv[1], table);
  unsigned int charCode = strtol(argv[2], NULL, 16);

  if (table.find(charCode) != table.end()) {
    std::vector<unsigned int> r = table[charCode];
    Show(r);
    return 0;
  }
  else {
    return 1;
  }
}

bool LoadCharTable(const char* path, std::map<unsigned int, std::vector<unsigned int> > &r) {
  FILE* fp = fopen(path, "r");
  if (!fp) {
    printf("ERROR! Bad file!\n");
    exit(1);
  }

  static char buffer[1024];
  std::vector<unsigned int> code(20);
  unsigned int charCode;
  while(fgets(buffer, 1024, fp)) {
    charCode = Line2Code(buffer, code);
    r[charCode] = code;
  }
  
  fclose(fp);
  return true;
}

void Show(const std::vector<unsigned int>& ch) {
  assert(ch.size() == 20);

  printf("%04x", ch[0]);

  for (size_t i = 1; i < 20; ++i) {
    printf(",%04x", ch[i]);
  }
}


unsigned int Line2Code(char *line, std::vector<unsigned int> &code) {
  std::string charCode(line, 4);
  unsigned int r = strtol(charCode.c_str(), NULL, 16);

  char *start = line + 5;
  char *comma = start;
  int i = 0;

  while(*comma) {
    while(*comma != '\n' && *comma != ',') ++comma;
    std::string t(start, comma-start);
    if (i >= 20) {
      break;
    }
    code[i++] = strtol(t.c_str(), NULL, 16);
    start = comma + 1;
    comma = start;
  }

  return r;
}
